import React, { useEffect, useState } from "react";
import './repay.css';
import '../../../App.css'
import { useHistory } from "react-router-dom/cjs/react-router-dom";
import { Mask, DotLoading } from "antd-mobile";
import { useDispatch } from "react-redux";
import icon_checked from "@/assets/icon_checked.png"
import icon_uncheck from "@/assets/icon_uncheck.png"
import icon_repay_rollover from "@/assets/icon_repay_rollover.png"
import AddHomeEvent from "@/utils/addHomeEvent";
import NavigateBarRepay from "@/components/NavigateBarRepay/NavigateBarRepay";
import { PageTag } from "@/utils/pageTag";
import { isLoanLoaning, isLoanReject, isLoanRepayNow, isLoanReviewing, isLoanSigning } from "@/utils/loanStatus";
import PaidAskDialog from "@/components/PaidAskDialog/PaidAskDialog";
import { reqRepayDetail, reqRepayUrl, reqSaveEvent, reqUserState } from "@/store/actions/apiServices";
import { isEmptyString } from "@/utils/utils";


/**
 * 还款页
 */
export default function Repay() {

    //loading状态
    const [maskVisible, setMaskVisible] = useState(false)

    //显示add home弹框
    const [addHomeMaskVisible, setAddHomeMaskVisible] = useState(false);
    const [addHomeMaskIsHomeMode, setAddHomeMaskIsHomeMode] = useState(true);

    //显示支付提示弹框
    const [paidAskMaskVisible, setPaidAskMaskVisible] = useState(false);

    // 获取路由历史 history 对象
    const history = useHistory()

    //获取 Redux 分发器
    const dispatch = useDispatch()

    //获取Redux Store中的信息
    const [repayDetailInfo, setRepayDetailInfo] = useState({});


    const onReqUserStateCallback = (success, resObj) => {
        setMaskVisible(false);

        if (success && resObj) {
            //是否为签约中
            const isHomeSigning = isLoanSigning(resObj.signFlag, resObj.signOrderId);
            //是否为审核中
            const isHomeReviewing = isLoanReviewing(resObj.applyStatus);
            //是否为拒绝
            const isHomeReject = isLoanReject(resObj.applyStatus, resObj.orderStatus);
            //是否为放款中
            const isHomeLoaning = isLoanLoaning(resObj.orderStatus);
            //是否为待还款
            const isHomeRepay = isLoanRepayNow(resObj.orderStatus);
            //是否为待进件
            const isHomeNotLoan = ((!isHomeReviewing) && (!isHomeReject) && (!isHomeLoaning) && (!isHomeRepay));
            console.log("Launch-isHomeReviewing: " + isHomeReviewing);
            console.log("Launch-isHomeReject: " + isHomeReject);
            console.log("Launch-isHomeLoaning: " + isHomeLoaning);
            console.log("Launch-isHomeRepay: " + isHomeRepay);
            console.log("Launch-isHomeNotLoan: " + isHomeNotLoan);
            console.log("Launch-isHomeSigning: " + isHomeSigning);

            if (isHomeSigning) {
                history.replace('/guide');
            } else if (isHomeReviewing) {
                history.replace('/review');
            } else if (isHomeReject) {
                history.replace('/reject');
            } else if (isHomeLoaning) {
                history.replace('/loaning');
            } else if (isHomeRepay) {
                checkRepayInfo();
            } else {
                history.replace('/home');
            }
        }
    };

    // 点击add home监听
    const onHandleAddToHome = (type) => {
        if (type === 'home') {
            AddHomeEvent.onHandleAddHomeEventClick()
        } else {
            AddHomeEvent.onHandleAddFavoriteEventClick()
        }
    }

    // 关闭add home
    const onHandleAddToHomeClose = () => {
        setAddHomeMaskVisible(false)
    }

    const onHandleRefresh = () => {
        checkUserStateInfo()
    }

    // 关闭支付提示弹框
    const onHandlePaidAskDialogClose = () => {
        setPaidAskMaskVisible(false)
    }

    //已支付
    const onHandleDidPaid = () => {
        setPaidAskMaskVisible(false)
        checkUserStateInfo()
    }

    // 未支付
    const onHandleNotPaid = () => {
        setPaidAskMaskVisible(false)
    }

    //点击提交
    const onHandleSubmit = () => {
        try {
            reqSaveEvent("REPAY_COMMIT_CLICK");

            setMaskVisible(true);
            reqRepayUrl((success, resObj) => {
                setMaskVisible(false);
                if (success && resObj) {
                    setPaidAskMaskVisible(true)
                    setTimeout(() => {
                        const url = resObj.url || "";
                        const repayUrl = resObj.repayUrl || "";
                        if (!isEmptyString(url)) {
                            window.open(url, "_blank");

                        } else if (!isEmptyString(repayUrl)) {
                            window.open(repayUrl, "_blank");
                        }
                    }, 500);
                }
            });
        } catch (e) {
            console.log(e)
        }
    }
    //查询用户流程状态
    const checkUserStateInfo = async () => {
        try {
            setMaskVisible(true);
            reqUserState(PageTag.REPAY, onReqUserStateCallback);

        } catch (e) {
            console.log(e)
        }
    }

    //查询还款信息
    const checkRepayInfo = async () => {
        try {
            setMaskVisible(true);
            reqRepayDetail((success, resObj) => {
                setMaskVisible(false);
                if (success && resObj) {
                    setRepayDetailInfo(resObj);
                }
            });
        } catch (e) {
            console.log(e)
        }
    }

    useEffect(() => {
        try {
            reqSaveEvent("REPAY_START")
            checkUserStateInfo()

            return () => {
                reqSaveEvent("REPAY_END")
            }
        } catch (e) {
            console.log(e)
        }
    }, [])

    return (
        <div className="repayRoot">
            <NavigateBarRepay theme="white" onAddFavorite={() => { setAddHomeMaskIsHomeMode(false); setAddHomeMaskVisible(true) }} onAddHome={() => { setAddHomeMaskIsHomeMode(true); setAddHomeMaskVisible(true) }} onRefresh={onHandleRefresh}>Loan repayment</NavigateBarRepay>

            <div className="repayTopEdge"></div>

            <div className="repayContent">

                <div className="repayContentScroll">
                    <div className="repayPlan">
                        <div className="repayPlanHeader">
                            <div className="repayPlanHeaderContent">
                                <img
                                    className="repayPlanHeaderIcon"
                                    src={icon_checked}
                                    alt="" />
                                <span className="repayItemHeaderTitle">Make payment in full:</span>
                            </div>
                            <span className="repayItemHeaderTips">You can borrow again immediately after repayment.</span>
                        </div>

                        <div className="repayItemList">
                            <div className="repayItemBillContent">
                                <span className="repayItemBillHeaderTitle">Total repayment</span>
                                <span className="repayItemBillHeaderAmount">{repayDetailInfo.repayAmount} {repayDetailInfo.currency}</span>
                                <span className="repayItemBillCurrency"></span>
                            </div>
                            <div className="repayItemBillContent">
                                <span className="repayItemBillHeaderTitle">Due date</span>
                                <span className="repayItemBillHeaderAmount">{repayDetailInfo.repayDate}</span>
                                <span className="repayItemBillCurrency"></span>
                            </div>

                            <span className='repayRowLine'></span>

                            <div className="repayItemBillContent">
                                <span className="repayItemBillItemTitle">Loan amount</span>
                                <span className="repayItemBillItemAmount">{repayDetailInfo.amount}</span>
                                <span className="repayItemBillCurrency">{repayDetailInfo.currency}</span>
                            </div>
                            <div className="repayItemBillContent">
                                <span className="repayItemBillItemTitle">Interest</span>
                                <span className="repayItemBillItemAmount">{repayDetailInfo.interest}</span>
                                <span className="repayItemBillCurrency">{repayDetailInfo.currency}</span>
                            </div>
                            <div className="repayItemBillContent">
                                <span className="repayItemBillItemTitle">Service fee</span>
                                <span className="repayItemBillItemAmount">{repayDetailInfo.repayProFee}</span>
                                <span className="repayItemBillCurrency">{repayDetailInfo.currency}</span>
                            </div>
                            <div className="repayItemBillContent">
                                <span className="repayItemBillItemTitle">Overdue days</span>
                                <span className="repayItemBillItemAmount">{repayDetailInfo.overdueDay}</span>
                                <span className="repayItemBillCurrency"> days</span>
                            </div>
                            <div className="repayItemBillContent">
                                <span className="repayItemBillItemTitle">Overdue penalty</span>
                                <span className="repayItemBillItemAmount">{repayDetailInfo.overdueAmount}</span>
                                <span className="repayItemBillCurrency">{repayDetailInfo.currency}</span>
                            </div>
                        </div>
                    </div>

                    {repayDetailInfo.canDeferred && <div className="repayPlan">
                        <div className="repayPlanHeader">
                            <div className="repayPlanHeaderContent">
                                <img
                                    className="repayPlanHeaderIcon"
                                    src={icon_uncheck}
                                    alt="" />
                                <span className="repayItemHeaderTitle">Rollover repayment:</span>
                            </div>
                            <span className="repayItemHeaderTips">After paying the extended service charges, your loan can be deferred for closing..</span>
                        </div>
                        <div className="repayItemList">
                            <div className="repayItemBillContent">
                                <span className="repayItemBillItemTitle">Extended service charges</span>
                                <span className="repayItemBillHeaderAmount">{repayDetailInfo.deferredRepay.currentRepayAmount} {repayDetailInfo.currency}</span>
                                <span className="repayItemBillCurrency"></span>
                            </div>
                            <div className="repayItemBillContent">
                                <span className="repayItemBillItemTitle">Days of extension</span>
                                <span className="repayItemBillHeaderAmount">{repayDetailInfo.deferredRepay.days}</span>
                                <span className="repayItemBillCurrency"> days</span>
                            </div>

                            <div className="repayItemBillContent">
                                <span className="repayItemBillHeaderTitle">Due date after extension</span>
                            </div>
                            <div className="repayItemBillContent">
                                <span className="repayRolloverTitle">{repayDetailInfo.deferredRepay.currentRepayTime}</span>
                                <img
                                    className="repayRolloverIcon"
                                    src={icon_repay_rollover}
                                    alt="" />
                                <span className="repayItemBillItemTitle">{repayDetailInfo.deferredRepay.deferredRepayTime}</span>
                            </div>

                            <div className="repayItemBillContent">
                                <span className="repayItemBillHeaderTitle">Total repayment due</span>
                            </div>
                            <div className="repayItemBillContent">
                                <span className="repayItemBillHeaderTitle">{repayDetailInfo.deferredRepay.deferredRepayAmount} {repayDetailInfo.currency}</span>
                            </div>
                        </div>
                    </div>}

                </div>
                <div className="repaySection"></div>
            </div>

            <div className="repayBottom">
                <div className="repayBottomAmountContent">
                    <span className="repayBottomAmountTitle">Payment amount</span>
                    <span className="repayBottomAmount">{repayDetailInfo.repayAmount} {repayDetailInfo.currency}</span>
                </div>
                <button type="submit" className="repayApplyBtn mainButtonGradient" onClick={onHandleSubmit}>Pay</button>
            </div>

            {/* <AddToHomeGifDialog visible={addHomeMaskVisible} onConfirm={onHandleAddToHome} onClose={onHandleAddToHomeClose} isHomeMode={addHomeMaskIsHomeMode} /> */}

            <PaidAskDialog visible={paidAskMaskVisible} onClose={onHandlePaidAskDialogClose} onDidPaid={onHandleDidPaid} onNotPaid={onHandleNotPaid} />

            <Mask visible={maskVisible} opacity={0.1}
                onMaskClick={() => { }}>
                <div className="overlayContent">
                    <span style={{ fontSize: 24, color: '#ff3141' }} >
                        <DotLoading color="currentColor" />
                    </span>
                </div>
            </Mask>
        </div >
    )
}